import { useState,useEffect } from "react";
import { useParams,useNavigate } from "react-router-dom";
import { updateStudent,addStudent } from "../redux/slice";
import { useDispatch,useSelector } from "react-redux";

function AddOrEdit() {
  const dispatch = useDispatch()
  const stuList = useSelector((state)=>state.stuList)
  const navigate = useNavigate()
  const params = useParams()
  const stuId = params.id
  const [stu,setStu] = useState({
    name:'',
    age:'',
    email:'',
    number:''
  })

    // 查询 id 的学生
  useEffect(()=>{
    if(stuId){
      for(let i=0;i<stuList.length;i++){
        if(stuList[i].id === stuId){
          setStu(stuList[i])
          break
        }
      }
    }
  },[stuId,stuList])

  
  const handleSubmit = async function(e){
    e.preventDefault()
    for(let key in stu){
      if(stu[key] === ''){
        alert('请完善表单再提交！')
        return
      }
    }
    if(stuId){
      dispatch(updateStudent({stuId,stu}))
    }
    else{
      dispatch(addStudent(stu))
    }
    navigate('/home')
  }

  const handleChange = function(target,key){
    const newStu = {
      ...stu
    }
    newStu[key] = target.value
    setStu(newStu)
  }

  return ( 
    <div>
      <h1>{params.id!=='' ? '修改用户' : '添加用户'}</h1>
      <div>
        <form onSubmit={(e)=>{handleSubmit(e)}}>
          <div className="form-group">
            <label >姓名</label>
            <input type="text" className="form-control"  placeholder="姓名" value={stu.name} onChange={(e)=>{handleChange(e.target,'name')}}/>
          </div>
          <div className="form-group">
            <label >年龄</label>
            <input type="text"  placeholder="年龄" value={stu.age} onChange={(e)=>{handleChange(e.target,'age')}}/>
          </div>
          <div className="form-group">
            <label >邮箱地址</label>
            <input type="email" className="form-control"id="exampleInputEmail1" placeholder="邮箱" value={stu.email} onChange={(e)=>{handleChange(e.target,'email')}}/>
          </div>
          <div className="form-group">
            <label >联系方式</label>
            <input type="text" id="exampleInputFile" value={stu.number} onChange={(e)=>{handleChange(e.target,'number')}}/>
          </div>
          
          <button type="submit" className="btn btn-default">Submit</button>
        </form>
      </div>
    </div>
   );
}

export default AddOrEdit;